package com.ev.apis.controller.asl;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.apis.model.DsResultResponse;
import com.ev.asl.constant.AslConstant;
import com.ev.asl.domain.AssemblyInstructionDO;
import com.ev.asl.domain.CheckResultDO;
import com.ev.asl.domain.MoldingDailyDO;
import com.ev.asl.domain.MoldingProductionInstructionDO;
import com.ev.asl.dto.CheckResultDto;
import com.ev.asl.service.AssemblyInstructionService;
import com.ev.asl.service.CheckResultService;
import com.ev.asl.service.MoldingDailyService;
import com.ev.asl.service.MoldingProductionInstructionService;
import com.ev.asl.vo.CheckResult2VO;
import com.ev.asl.vo.CheckResult3VO;
import com.ev.asl.vo.CheckResultVO;
import com.ev.custom.service.MaterielService;
import com.ev.custom.service.NoticeService;
import com.ev.framework.annotation.EvApiByToken;
import com.ev.framework.config.Constant;
import com.ev.framework.config.ConstantForDevice;
import com.ev.framework.utils.*;
import com.ev.k3cloudBusiness.dto.ErpInOrOutStockParam;
import com.ev.k3cloudBusiness.service.impl.SyncPushBillAdapter;
import com.ev.k3cloudBusiness.vo.KisApiResultVOS;
import com.ev.mes.dao.CheckPlanItemDao;
import com.ev.system.domain.UserDO;
import com.ev.system.service.UserService;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 检查成绩api接口
 * @author 姚家乐
 * @since 2021/6/18 12:55
 */
@Api(value = "/", tags = "检查成绩api")
@RestController
@Slf4j
public class CheckResultApiController {

    @Autowired
    private CheckResultService                  service;

    @Autowired
    private MoldingProductionInstructionService mpiService;

    @Autowired
    private MoldingDailyService moldingDailyService;

    @Autowired
    private AssemblyInstructionService          aiService;

    @Autowired
    private CheckPlanItemDao                    checkPlanItemDao;

    @Autowired
    private MaterielService                     materielService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private UserService userService;

    @Autowired
    private SyncPushBillAdapter syncPushBillAdapter;

    /**
     * 根据指示书生成首检
     * 该接口只针对成型，组装没有首检了
     */
    @EvApiByToken(value = "/apis/CheckResult/insertFirstInspection", method = RequestMethod.POST, apiTitle = "根据指示书生成首检")
    @ApiOperation("根据指示书生成首检")
    @Transactional
    public R insertFirstInspection(@ApiParam(value = "主键ID") @RequestParam("id") Long id,
                                   @ApiParam(value = "1:成型，2：组装") @RequestParam(value = "isChooseShow") Integer isChooseShow,
                                   @ApiParam(value = "规格型号") @RequestParam(value = "specification",required = false,defaultValue = "") String specification){

        CheckResultDto dto = new CheckResultDto();
        dto.setType(AslConstant.NO);

        Map<String,Object> param = new HashMap<>();
//        param.put("isChooseShow",isChooseShow);
        param.put("type",0);
        param.put("instructionId",id);

        //int total = service.countForMap(param);
        //if (total > AslConstant.ZERO) {
        //    return R.error("一份指示书不能重复添加首检");
        //}
        log.error("==================================1");
        if (AslConstant.ONE.equals(isChooseShow)){
            log.error("==================================2");
            MoldingProductionInstructionDO mpiDo = mpiService.get(id);
            dto.setInstructionId(mpiDo.getId());
            dto.setBillDate(new Date());
            dto.setInstructionNo(mpiDo.getMpiNo());
            dto.setProductId(mpiDo.getMaterielId());
            dto.setProduct(mpiDo.getMaterielName());
            dto.setIsChooseShow(isChooseShow);
            dto.setDailyNo(mpiDo.getMpiNo());
            dto.setSpecification(specification);
            Map<String,Object> materielMap = materielService.getDetail(mpiDo.getMaterielId());
            if (ObjectUtils.isEmpty(materielMap) || !materielMap.containsKey("checkPlanId")){
                return R.error("物料未添加检验方案");
            }

            mpiDo.setHaveFirstCheck(AslConstant.YES);
            mpiService.update(mpiDo);
        }else {
            return R.error("不是成型指示书");
        }
        service.save2(dto,isChooseShow);

        return R.ok();
    }

    /**
     * 根据成型日报生成首检
     * 该接口只针对成型，组装没有首检了
     */
    @EvApiByToken(value = "/apis/CheckResult/insertFirstInspection2", method = RequestMethod.POST, apiTitle = "根据指示书生成首检")
    @ApiOperation("根据指示书生成首检")
    @Transactional
    public R insertFirstInspection2(@ApiParam(value = "成型日报主键ID") @RequestParam("id") Long id){

        CheckResultDto dto = new CheckResultDto();
        dto.setType(AslConstant.NO);

        Map<String,Object> param = new HashMap<>();
//        param.put("isChooseShow",isChooseShow);
        param.put("type",0);
        param.put("instructionId",id);

        //int total = service.countForMap(param);
        //if (total > AslConstant.ZERO) {
        //    return R.error("一份指示书不能重复添加首检");
        //}
        MoldingDailyDO moldingDailyDO = moldingDailyService.get(id);
        log.error("==================================1");
        MoldingProductionInstructionDO mpiDo = mpiService.get(moldingDailyDO.getMpiId());
        Map<String,Object> materielMap = materielService.getDetail(mpiDo.getMaterielId());
        if (ObjectUtils.isEmpty(materielMap) || !materielMap.containsKey("checkPlanId")){
            return R.error("物料未添加检验方案");
        }
        dto.setInstructionId(mpiDo.getId());
        String batchNo = (ObjectUtil.isEmpty(moldingDailyDO.getLotNoEnd()) ? "" : moldingDailyDO.getLotNoEnd()) + (ObjectUtil.isEmpty(moldingDailyDO.getLotNoStart()) ? "" : moldingDailyDO.getLotNoStart());
        dto.setBatchNo(batchNo);
        dto.setBillDate(new Date());
        dto.setInstructionQty(moldingDailyDO.getInstructionQty());
        dto.setInstructionNo(mpiDo.getMpiNo());
        dto.setProductId(mpiDo.getMaterielId());
        dto.setProduct(mpiDo.getMaterielName());
        dto.setIsChooseShow(1);
        dto.setDailyNo(mpiDo.getMpiNo());
        mpiDo.setHaveFirstCheck(AslConstant.YES);
        mpiService.update(mpiDo);
        service.save2(dto,1);

        return R.ok();
    }
//    /**
//     * 根据指示书生成首检
//     * 该接口只针对成型，组装没有首检了
//     */
//    @EvApiByToken(value = "/apis/CheckResult/insertFirstInspection", method = RequestMethod.POST, apiTitle = "根据指示书生成首检")
//    @ApiOperation("根据指示书生成首检")
//    @Transactional
//    public R insertFirstInspection(@ApiParam(value = "主键ID") @RequestParam("id") Long id,
//                                   @ApiParam(value = "1:成型，2：组装") @RequestParam(value = "isChooseShow") Integer isChooseShow){
//
//        CheckResultDto dto = new CheckResultDto();
////        dto.setBillDate(new Date());
//        dto.setType(AslConstant.NO);
////        dto.setResult(AslConstant.NO);
//
//        Map<String,Object> param = new HashMap<>();
//        param.put("isChooseShow",isChooseShow);
//        param.put("type",0);
//        param.put("instructionId",id);
//
//        int total = service.countForMap(param);
//        if (total > AslConstant.ZERO) {
//            return R.error("一份指示书不能重复添加首检");
//        }
//        log.error("==================================1");
//        if (AslConstant.ONE.equals(isChooseShow)){
//            log.error("==================================2");
//            MoldingProductionInstructionDO mpiDo = mpiService.get(id);
//            dto.setInstructionId(mpiDo.getId());
//            dto.setBillDate(mpiDo.getIndicateDate());
//            dto.setInstructionNo(mpiDo.getMpiNo());
//            dto.setProductId(mpiDo.getMaterielId());
//            dto.setProduct(mpiDo.getMaterielName());
//            dto.setIsChooseShow(isChooseShow);
////            dto.setInstructionQty(mpiDo.getAGroupNumber());
//            dto.setDailyNo(mpiDo.getMpiNo());
////            dto.setDetailDOS(this.getDetail(mpiDo.getMaterielId()));
//            Map<String,Object> materielMap = materielService.getDetail(mpiDo.getMaterielId());
//            if (ObjectUtils.isEmpty(materielMap) || !materielMap.containsKey("checkPlanId")){
//                return R.error("物料未添加检验方案");
//            }
////            dto.setDetailDOS(this.getDetail2(materielMap));
//
//            //todo 检查状态使用情况
//            mpiDo.setHaveFirstCheck(AslConstant.YES);
//            mpiService.update(mpiDo);
//        }
//        if(AslConstant.TWO.equals(isChooseShow)){
//            log.error("==================================3");
//            AssemblyInstructionDO aiDo = aiService.get(id);
//            dto.setInstructionId(aiDo.getId());
//            dto.setBillDate(aiDo.getIndicateDate());
//            dto.setInstructionNo(aiDo.getSerialNo());
//            dto.setProductId(aiDo.getMaterielId());
//            dto.setProduct(aiDo.getMaterielName());
//            dto.setIsChooseShow(isChooseShow);
////            dto.setDetailDOS(this.getDetail(aiDo.getMaterielId()));
//            Map<String,Object> materielMap = materielService.getDetail(aiDo.getMaterielId());
//            if (ObjectUtils.isEmpty(materielMap) || !materielMap.containsKey("checkPlanId")){
//                return R.error("物料未添加检验方案");
//            }
////            dto.setDetailDOS(this.getDetail2(materielMap));
//
//            aiDo.setHaveFirstCheck(AslConstant.YES);
//            aiService.update(aiDo);
//        }
//        service.save2(dto,isChooseShow);
//
//        return R.ok();
//    }

    private String getDetail(Long materielId){
        Map<String,Object> materielMap = materielService.getDetail(materielId);
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(1);
        params.put("id",Long.parseLong(String.valueOf(materielMap.get("checkPlanId"))));
        List<Map<String, Object>> details = checkPlanItemDao.listOfDetail(params);

        List<Map<String, Object>> newDetails = new ArrayList<>();
        Map<String,Object> map;
        for (Map<String,Object> detailMap : details) {
            map = new HashMap<>();
            map.put("remark",detailMap.get("remark"));
            map.put("name",detailMap.get("name"));
            map.put("projectId",detailMap.get("projectId"));
            map.put("typeDictionaryId",detailMap.get("typeDictionaryId"));
            map.put("method",detailMap.get("method"));
            map.put("sample",null);
            map.put("targetValue",detailMap.get("targetValue"));
            newDetails.add(map);
        }
        return JSON.toJSONString(newDetails);
    }
    private String getDetail2(Map<String,Object> materielMap){
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(1);
        params.put("id",Long.parseLong(String.valueOf(materielMap.get("checkPlanId"))));
        List<Map<String, Object>> details = checkPlanItemDao.listOfDetail(params);

        List<Map<String, Object>> newDetails = new ArrayList<>();
        Map<String,Object> map;
        for (Map<String,Object> detailMap : details) {
            map = new HashMap<>();
            map.put("remark",detailMap.get("remark"));
            map.put("name",detailMap.get("name"));
            map.put("projectId",detailMap.get("projectId"));
            map.put("typeDictionaryId",detailMap.get("typeDictionaryId"));
            map.put("method",detailMap.get("method"));
            map.put("sample",null);
            map.put("targetValue",detailMap.get("targetValue"));
            newDetails.add(map);
        }
        return JSON.toJSONString(newDetails);
    }


    /**
     * 保存检查成绩信息
     *
     * @date 2019-11-27
     * @author gumingjie
     */
    @Transactional(rollbackFor = Exception.class)
    @EvApiByToken(value = "/apis/CheckResult/save", method = RequestMethod.POST, apiTitle = "保存检查成绩信息")
    @ApiOperation("保存检查成绩信息")
    @ApiImplicitParams({ @ApiImplicitParam(name = "billDate", value = "日期", dataType = "Date"),
                         @ApiImplicitParam(name = "dailyId", value = "日报ID", dataType = "Integer"),
                         @ApiImplicitParam(name = "dailyNo", value = "日报编号", dataType = "String"),
                         @ApiImplicitParam(name = "productId", value = "产品ID", dataType = "Integer"),
                         @ApiImplicitParam(name = "product", value = "产品", dataType = "String"),
                         @ApiImplicitParam(name = "batchNo", value = "批号", dataType = "String"),
                         @ApiImplicitParam(name = "result", value = "结果（0：合格，1：:不合格）", dataType = "Integer"),
                         @ApiImplicitParam(name = "type", value = "类型（0：首检，1：:终检）", dataType = "Integer"),
                         @ApiImplicitParam(name = "isChooseShow", value = "1:成型，2：组装", dataType = "Integer") })
    public R save(CheckResultDto dto) {
        if (service.save(dto) > AslConstant.ZERO) {
            Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
            result.put("id", dto.getId());
            return R.ok(result);
        }
        return R.error();
    }

    /**
     * 审查检查成绩信息
     *
     * @date 2019-11-27
     * @author gumingjie
     */
    @Transactional(rollbackFor = Exception.class)
    @EvApiByToken(value = "/apis/CheckResult/check", method = RequestMethod.POST, apiTitle = "审查检查成绩信息")
    @ApiOperation("审查检查成绩信息")
    public R check(@RequestBody CheckResult3VO checkResult3VO) {
        return service.check(checkResult3VO);
    }

    /**
     * 查看检查成绩详情
     *
     * @date 2019-11-27
     * @author gumingjie
     */
    @EvApiByToken(value = "/apis/CheckResult/detail", method = RequestMethod.POST, apiTitle = "查看检查成绩详情")
    @ApiOperation("查看检查成绩详情")
    public R detail(@ApiParam(value = "检查成绩Id", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        return R.ok(service.getDetailInfo(id));
    }

    @EvApiByToken(value = "/apis/CheckResult/printDetail", method = RequestMethod.POST, apiTitle = "打印")
    @ApiOperation("打印")
    public R printDetail(@ApiParam(value = "检查成绩Id", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        return R.ok(service.printDetailOfResult(id));
    }

    /**
     * 修改检查成绩
     * @param dto
     * @return
     */
    @EvApiByToken(value = "/apis/CheckResult/update", method = RequestMethod.POST, apiTitle = "修改检查成绩")
    @ApiOperation("修改检查成绩")
    public R update(CheckResultDto dto) {
        CheckResultDO checkResultDO = service.get(dto.getId());
        if (AslConstant.NO.equals(checkResultDO.getStatus())) {

            dto.setQualityInspectorId(ShiroUtils.getUserId());
            dto.setQualityInspectorName(ShiroUtils.getUser().getUsername());
            int update = service.update(dto);
            if (update > AslConstant.ZERO) {
                return R.ok();
            }
            return R.error();
        }
        if(Objects.equals(checkResultDO.getStatus(),AslConstant.TWO)){
            return R.error("已提交状态不能修改！");
        }
        return R.error("已批准状态不能修改！");
    }

    @ResponseBody
    @EvApiByToken(value = "/apis/checkResult/checkResultOut", method = RequestMethod.GET, apiTitle = "导出生产入库")
    @ApiOperation("导出检查成绩单")
    public void exportExcel(
            @ApiParam(value = "检查成绩单id") @RequestParam(value = "id", defaultValue = "", required = false) Long  id,
            HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {


        Map<String,Object> map = Maps.newHashMap();
        ClassPathResource classPathResource = new ClassPathResource("poi/inspection_result.xlsx");
        TemplateExportParams params = new TemplateExportParams(
                "poi/inspection_result.xlsx", true);
        TemplateExportParams result = new TemplateExportParams(classPathResource.getPath());
        Workbook book = ExcelExportUtil.exportExcel(result, map);
        modelMap.put(TemplateExcelConstants.FILE_NAME, "检查成绩书");
        modelMap.put(TemplateExcelConstants.PARAMS, result);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);


    }

    /**
     * 删除
     */
    @EvApiByToken(value = "/apis/CheckResult/batchRemove", method = RequestMethod.GET, apiTitle = "删除检查成绩")
    @ApiOperation("删除检查成绩")
    public R batchRemove(@RequestParam("ids") Long[] ids) {
        int remove = service.batchRemove(ids);
        if (remove > AslConstant.ZERO) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }

    /**
     * 删除
     */
    @EvApiByToken(value = "/apis/CheckResult/remove", method = RequestMethod.GET, apiTitle = "删除检查成绩")
    @ApiOperation("删除检查成绩")
    public R remove(@RequestParam("id") Long id) {
        CheckResultDO checkResultDO = service.get(id);
        if (AslConstant.NO.equals(checkResultDO.getStatus())) {
            int remove = service.remove(id);
            if (remove > AslConstant.ZERO) {
                return R.ok("删除成功");
            }
            return R.error("删除失败");
        }
        return R.error("此状态不能删除！");
    }

    @EvApiByToken(value = "/apis/CheckResult/submit", method = RequestMethod.POST, apiTitle = "提交检查成绩")
    @ApiOperation("提交检查成绩")
    @Transactional(rollbackFor = Exception.class)
    public R submit(CheckResultDto checkResultDto){
        CheckResultDO checkResultDO = service.get(checkResultDto.getId());
        if (AslConstant.NO.equals(checkResultDO.getStatus())) {
            checkResultDto.setQualityInspectorId(ShiroUtils.getUserId());
            checkResultDto.setQualityInspectorName(ShiroUtils.getUser().getUsername());
            checkResultDto.setStatus(AslConstant.TWO);
            int update = service.update(checkResultDto);
            if (update > AslConstant.ZERO && checkResultDO.getType() != 2) {
                String title = "@我的检查成绩书";
                String content = "您好，" + Objects.requireNonNull(ShiroUtils.getUser()).getName() + "的检查成绩书已完成，请及时处理";
                JSONObject contentDetail = new JSONObject();
                contentDetail.put("id", checkResultDO.getId());
                contentDetail.put("url", "/basic/check_grade_add?id="+checkResultDO.getId());
                List<Long> toUsers = new ArrayList<>();
                toUsers.add(Constant.QUALITY_DEPT_MANAGER);    //通知张少明
                try {
                    noticeService.saveAndSendSocket(title, content, checkResultDO.getId(), contentDetail.toString(), 55L, ShiroUtils.getUserId(), toUsers);
                } catch (Exception e) {
                    log.error("==============================发送检查成绩书的提醒消息失败。id:" + checkResultDO.getId());
                    e.printStackTrace();
                }
                return R.ok();
            }else if(update > AslConstant.ZERO && checkResultDO.getType() == 2){
                String title = "@我的过期检验单";
                String content = "您好，" + Objects.requireNonNull(ShiroUtils.getUser()).getName() + "已发送原料检验，请及时处理";
                JSONObject contentDetail = new JSONObject();
                contentDetail.put("id", checkResultDO.getId());
                contentDetail.put("url", "/basic/expiredInspectionAdd?id="+checkResultDO.getId());
                List<Long> toUsers = new ArrayList<>();
                toUsers.add(Constant.QUALITY_DEPT_MANAGER);    //通知张少明
                try {
                    noticeService.saveAndSendSocket(title, content, checkResultDO.getId(), contentDetail.toString(), 55L, ShiroUtils.getUserId(), toUsers);
                } catch (Exception e) {
                    log.error("==============================发送过期检验的提醒消息失败。id:" + checkResultDO.getId());
                    e.printStackTrace();
                }
                return R.ok();
            }
            return R.error();
        }
        if (Objects.equals(checkResultDO.getStatus(),AslConstant.TWO)){
            return R.error("已提交，不能重复提交！");
        }
        return R.error("已批准，不能重复提交！");
    }

    @EvApiByToken(value = "/apis/CheckResult/overrule", method = RequestMethod.GET, apiTitle = "驳回检查成绩")
    @ApiOperation("驳回检查成绩")
    @Transactional(rollbackFor = Exception.class)
    public R overrule(@ApiParam(value = "检查成绩id", required = true) @RequestParam("id") Long id) {
        CheckResultDO checkResultDO = service.get(id);
        if(Objects.equals(checkResultDO.getStatus(), AslConstant.ONE)){
            return R.error("已批准，不能驳回！");
        }
        if(Objects.equals(checkResultDO.getStatus(),AslConstant.ZERO)){
            return R.error("未提交，不能驳回！");
        }
        checkResultDO.setStatus(AslConstant.ZERO);
        Integer update = service.update(checkResultDO);
        if (update > AslConstant.ZERO && checkResultDO.getType() != 2) {
            String title = "@我的检查成绩书";
            String content = "您好，" + Objects.requireNonNull(userService.get(checkResultDO.getCreateBy()).getName()) + "的检查成绩书已驳回，请及时处理";
            JSONObject contentDetail = new JSONObject();
            contentDetail.put("id", checkResultDO.getId());
            contentDetail.put("url", "/basic/check_grade_add?id="+checkResultDO.getId());
            List<Long> toUsers = new ArrayList<>();
            toUsers.add(checkResultDO.getCreateBy());    //通知张少明
            try {
                noticeService.saveAndSendSocket(title, content, checkResultDO.getId(), contentDetail.toString(), 55L, ShiroUtils.getUserId(), toUsers);
            } catch (Exception e) {
                log.error("==============================发送检查成绩书驳回的提醒消息失败。id:" + checkResultDO.getId());
                e.printStackTrace();
            }
            return R.ok();
        }else if(update > AslConstant.ZERO && checkResultDO.getType() == 2){
            String title = "@我的过期检验单";
            String content = "您好，" + Objects.requireNonNull(ShiroUtils.getUser()).getName() + "已驳回原料检验，请及时处理";
            JSONObject contentDetail = new JSONObject();
            contentDetail.put("id", checkResultDO.getId());
            contentDetail.put("url", "/basic/expiredInspectionAdd?id="+checkResultDO.getId());
            List<Long> toUsers = new ArrayList<>();
            toUsers.add(Constant.QUALITY_DEPT_MANAGER);    //通知张少明
            try {
                noticeService.saveAndSendSocket(title, content, checkResultDO.getId(), contentDetail.toString(), 55L, ShiroUtils.getUserId(), toUsers);
            } catch (Exception e) {
                log.error("==============================发送过期检验驳回的消息失败。id:" + checkResultDO.getId());
                e.printStackTrace();
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 批准
     */
    @EvApiByToken(value = "/apis/CheckResult/ratify", method = RequestMethod.GET, apiTitle = "批准检查成绩")
    @ApiOperation("批准检查成绩")
    @Transactional(rollbackFor = Exception.class)
    public R ratify(@RequestParam("id") Long id, HttpServletRequest request) {
        UserDO userDO = ShiroUtils.getUser();

        CheckResultDO checkResultDO = service.get(id);
        if (AslConstant.YES.equals(checkResultDO.getStatus())) {
            return R.error("已批准，不能多次批准！");
        }
        if(AslConstant.NO.equals(checkResultDO.getStatus())){
            return R.error("未提交，不能进行批准");
        }
        checkResultDO.setStatus(AslConstant.YES);
        checkResultDO.setQualityBearerId(userDO.getUserId());
        checkResultDO.setQualityBearerName(userDO.getName());
        int update = service.update(checkResultDO);
        if (update > AslConstant.ZERO) {
            if(checkResultDO.getType() ==2){
                if(this.allocationBack(id)){
                    return R.ok();
                }else{
                    throw new BDException("库存调拨失败，请先确认库存！");
                }
            }
            return R.ok();
        }
        return R.error();
    }

    @EvApiByToken(value = "/apis/CheckResult/returnBack", method = RequestMethod.GET, apiTitle = "调拨返回")
    @ApiOperation("调拨返回")
    @Transactional(rollbackFor = Exception.class)
    public R returnBack(@ApiParam(value = "过期检验id", required = true) @RequestParam("id") Long id) {
        CheckResultDO checkResultDO = service.get(id);
        if(this.allocationBack(id)){
            checkResultDO.setStatus(AslConstant.YES);
            service.update(checkResultDO);
            return R.ok();
        }else{
            throw new BDException("库存调拨失败，请先确认库存！");
        }
    }

    private boolean allocationBack(Long id) {
        CheckResultDO checkResultDO = service.get(id);
        log.info("==========================过期库存,开始反调拨======================================");
        ErpInOrOutStockParam param = new ErpInOrOutStockParam();
        List<ErpInOrOutStockParam> params = new ArrayList<>();
        param.setMaterialId(checkResultDO.getProductId().intValue());
        param.setQty(checkResultDO.getQty());
        param.setBatch(checkResultDO.getBatchNo());
        param.setWarehouseId(Constant.warehouse10.intValue());
//        param.setWarehItemId(Integer.parseInt(kisReceiveStockVo.getFStockPlaceID()));
        param.setMoveInWarehouseId(Constant.warehouse2.intValue());
        params.add(param);
        KisApiResultVOS vos = syncPushBillAdapter.inventoryTransfer(params);
//        JSONArray jsonArray = new JSONArray(vos.getMsg());
        System.out.println(JSON.toJSONString(vos));
        if(vos.getStatus() == 0){
            log.info("==========================库存挑拨完成======================================");
            return true;
        }else {
            log.info("==========================调拨失败,跳过======================================");
            log.error(vos.getMsg());
            return false;
        }
    }


    /**
     * 查看检查成绩分页列表
     * @param pageno
     * @param pagesize
     * @param delFlag
     * @param checkNo
     * @param product
     * @param billDateStart
     * @param billDateStart
     * @param billDateEnd
     * @return
     */
    @EvApiByToken(value = "/apis/CheckResult/list", method = RequestMethod.POST, apiTitle = "查看检查成绩分页列表")
    @ApiOperation("查看检查成绩分页列表")
    public R list(@ApiParam(value = "当前第几页", required = true) @RequestParam(value = "pageno", defaultValue = "1") int pageno,
                  @ApiParam(value = "一页多少条", required = true) @RequestParam(value = "pagesize", defaultValue = "20") int pagesize,
                  @ApiParam(value = "刪除状态") @RequestParam(value = "delFlag", defaultValue = "", required = false) Integer delFlag,
                  @ApiParam(value = "检查编号") @RequestParam(value = "checkNo", defaultValue = "", required = false) String checkNo,
                  @ApiParam(value = "状态") @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
                  @ApiParam(value = "品名") @RequestParam(value = "product", defaultValue = "", required = false) String product,
                  @ApiParam(value = "物料名称") @RequestParam(value = "materialName", defaultValue = "", required = false) String materialName,
                  @ApiParam(value = "检验类型") @RequestParam(value = "type", defaultValue = "", required = false) Integer type,
                  @ApiParam(value = "日期的起始时间") @RequestParam(value = "billDateStart", defaultValue = "", required = false) Date billDateStart,
                  @ApiParam(value = "日期的结束时间") @RequestParam(value = "billDateEnd", defaultValue = "", required = false) Date billDateEnd) {

        Map<String, Object> params = Maps.newHashMapWithExpectedSize(8);
        params.put("offset", (pageno - AslConstant.ONE) * pagesize);
        params.put("limit", pagesize);
        params.put("delFlag", delFlag);
        params.put("status", status);
        params.put("checkNo", checkNo);
        params.put("product", product);
        params.put("materialName", materialName);
        params.put("billDateStart", billDateStart);
        params.put("billDateEnd", billDateEnd);
        params.put("type", type);
        int total = service.countForMap(params);
        if (total > AslConstant.ZERO){
            Map<String, Object> results = Maps.newHashMapWithExpectedSize(1);
            List<Map<String, Object>> data = service.listForMap(params);
            for (Map<String, Object> map : data) {
                if(!ObjectUtils.isEmpty(map.get("specification"))){
                    map.put("product",map.get("product") + "-" + map.get("specification"));
                }
                map.put("billDate", DateUtils.format((Date) map.get("billDate")));
            }
            results.put("data", new DsResultResponse(pageno, pagesize, total, data));
            return R.ok(results);
        }
        return R.ok();
    }

    @EvApiByToken(value = "/apis/CheckResult/list/exportExcel", method = RequestMethod.GET, apiTitle = "检查成绩分页列表(导出)")
    @ApiOperation("检查成绩分页列表(导出)")
    public void exportExcel(@ApiParam(value = "刪除状态") @RequestParam(value = "delFlag", defaultValue = "", required = false) Integer delFlag,
                            @ApiParam(value = "检查编号") @RequestParam(value = "checkNo", defaultValue = "", required = false) String checkNo,
                            @ApiParam(value = "状态") @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
                            @ApiParam(value = "品名") @RequestParam(value = "product", defaultValue = "", required = false) String product,
                            @ApiParam(value = "日期的起始时间") @RequestParam(value = "billDateStart", defaultValue = "", required = false) Date billDateStart,
                            @ApiParam(value = "日期的结束时间") @RequestParam(value = "billDateEnd", defaultValue = "", required = false) Date billDateEnd,
                            HttpServletRequest request, HttpServletResponse response,
                            ModelMap modelMap) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(6);
        params.put("delFlag", delFlag);
        params.put("checkNo", checkNo);
        params.put("status", status);
        params.put("product", product);
        params.put("billDateStart", billDateStart);
        params.put("billDateEnd", billDateEnd);
        List<Map<String, Object>> data = service.listForMap(params);
        if (!CollectionUtils.isEmpty(data)) {
            for (Map<String, Object> map : data) {
                map.put("billDateString", DateUtils.format((Date) map.get("billDate")));
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("list", JSONUtils.format(data));
            ClassPathResource classPathResource = new ClassPathResource("poi/check_result.xlsx");
            TemplateExportParams result = new TemplateExportParams(classPathResource.getPath());
            modelMap.put(TemplateExcelConstants.FILE_NAME, "检查成绩");
            modelMap.put(TemplateExcelConstants.PARAMS, result);
            modelMap.put(TemplateExcelConstants.MAP_DATA, map);
            PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
        }
    }
}
